import React, { Ref, useContext, useEffect, useMemo, useRef } from 'react';
import { OneModal } from '@/components/one-ui';
import MyIcon from '@/components/MyIcon';
import { useRequest } from '@@/plugin-request/request';
import { Form, Input, TreeSelect, InputNumber, message } from 'antd';
import { getCompanyID, getPosIDs, getUserDepID, getUserID } from '@/utils';
import fromStyle from '@/common/pageLayout.less';
import { IOneModalRef } from '@/pages/type';
import { IDictionaryEdit } from '../type';
import { DictionaryContext } from '../hooks';
import { editDictionary } from '../service';
import { DictionaryColorPicker } from './DictionaryColorPicker';

export const DictionaryEdit: React.FC<IDictionaryEdit> = ({
  onClose,
  dataSource,
  record,
}) => {
  const [form] = Form.useForm();

  /**
   * 弹框 ref
   */
  const dictionaryModalRef: Ref<IOneModalRef> = useRef(null); //弹框的ref
  /* 关闭弹窗 */
  const onCloseModal = () => {
    if (dictionaryModalRef) {
      if (dictionaryModalRef.current) {
        if (dictionaryModalRef.current.onModalCancel) {
          dictionaryModalRef.current.onModalCancel();
        }
      }
    }
  };

  const { selectKeys, reloadTableDataSource } = useContext(DictionaryContext);

  useEffect(() => {
    form.setFieldsValue({
      ...record,
    });
  }, [record]);

  const editRequest = useRequest(
    (params) => {
      return editDictionary(params);
    },
    {
      manual: true,
      onSuccess: (res) => {
        if (res && res?.msgFlag) {
          message.success(res?.msg);
        } else {
          message.error('编辑失败');
        }
        reloadTableDataSource(selectKeys?.[0]);
        // onClose();
        onCloseModal();
      },
    },
  );

  const getTreeIcon = (flag: any) => {
    return (
      <a style={{ marginRight: 5 }}>
        {flag ? (
          <MyIcon type={'icon-ic-normal-zidianguanli'} />
        ) : (
          <MyIcon type={'icon-icon-test2'} />
        )}
      </a>
    );
  };

  const treeData = useMemo(() => {
    let loop: any = (data: any[]) => {
      return data?.map((item) => {
        if (item?.children) {
          return {
            ...item,
            children: loop(item?.children),
            title: (
              <div style={{ display: 'flex', alignItems: 'center' }}>
                {getTreeIcon(item?.pID)}
                <span>{item?.name}</span>
              </div>
            ),
            value: item?.id,
          };
        }

        return {
          ...item,
          title: (
            <div style={{ display: 'flex', alignItems: 'center' }}>
              {getTreeIcon(item?.pID)}
              <span>{item?.name}</span>
            </div>
          ),
          value: item?.id,
        };
      });
    };

    return loop(dataSource) ?? [];
  }, [dataSource]);

  const onOk = () => {
    form.validateFields().then((res) => {
      if (res) {
        const typeID = selectKeys?.[0];

        const params = {
          isOpen: 1,
          isChoice: 1,
          isDisplay: 1,
          seq: res?.seq,
          pID: res?.pID,
          name: res?.name,
          typeID,
          shortCode: res?.shortCode,
          fontColor: res?.fontColor,
          remark: res?.remark,
          id: record?.id,
          modifyerID: getUserID(),
          modifyPositionID: getPosIDs(),
          modifyDepartmentID: getUserDepID(),
          modifyCompanyID: getCompanyID(),
          versionNum: record?.versionNum ?? 0,
        };

        editRequest.run(params);
      }
    });
  };

  return (
    <OneModal
      open={true}
      centered={true}
      onCancel={onClose}
      title={'编辑字典'}
      maskClosable={false}
      ref={dictionaryModalRef}
      onOk={onOk}
      okButtonProps={{
        loading: editRequest.loading,
      }}
      bodyStyle={{ padding: '5px 0px' }}
      getContainer={false}
    >
      <div className={fromStyle['fromView-styles']}>
        <Form form={form}>
          <Form.Item
            name="name"
            label="名称"
            rules={[
              {
                required: true,
                message: '请输入字典名称',
              },
            ]}
          >
            <Input placeholder={'请输入名称'} />
          </Form.Item>
          <Form.Item name="pID" label="上级字典">
            <TreeSelect treeData={treeData} placeholder={'请输入名称'} />
          </Form.Item>
          <Form.Item name="shortCode" label="简码">
            <Input placeholder={'请输入名称'} />
          </Form.Item>
          <Form.Item
            name="seq"
            label="排序"
            rules={[
              {
                required: true,
                message: '请输入排序',
                pattern: new RegExp('^[0-9][0-9]*$'),
              },
            ]}
          >
            <InputNumber placeholder={'请输入排序'} min={0} />
          </Form.Item>
          <Form.Item
            name="fontColor"
            label="字体颜色"
            rules={[
              {
                required: true,
                message: '请选择字体颜色',
              },
            ]}
          >
            <DictionaryColorPicker />
          </Form.Item>
          <Form.Item name="remark" label="备注">
            <Input.TextArea
              showCount
              maxLength={200}
              placeholder={'请输入备注'}
              autoSize={{ minRows: 2, maxRows: 4 }}
            />
          </Form.Item>
        </Form>
      </div>
    </OneModal>
  );
};
